#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>

#include "../getopt_helper.h"

static struct option const LONG_OPTIONS[] = {
	{ "null", no_argument, NULL, '0' }, GETOPT_END_DECL
};

static const char usage_str[] =
    "Usage: %s [OPTION]... [VARIABLE]...\n"
    "Print the values of the specified environment VARIABLE(s).\n"
    "If no VARIABLE is specified, print name and value pairs for them all.\n"
    "\n"
    "  -0, --null     end each output line with NUL, not newline\n"
    "      --help     display this help and exit\n"
    "      --version  output version information and exit\n"
    "\n"
    "NOTE: your shell may have its own version of printenv, which usually "
    "supersedes\n"
    "the version described here.  Please refer to your shell's documentation\n"
    "for details about the options it supports.";

int
main(int argc, char **argv)
{

	int ch;
	int matches = 0;

	size_t name_len;

	enum flag zero = NO;

	char *	      value;
	extern char **environ;
	char **	      env = environ;

	while ((ch = getopt_long(argc, argv, "0", LONG_OPTIONS, NULL)) != -1) {
		switch (ch) {
		case '0':
			zero = YES;
			break;

			GETOPT_END_CASE
		}
	}

	if (optind >= argc) {
		for (; *env; env++)
			printf("%s%c", *env, '\n' * !zero);

		return 0;
	}

	for (argv += optind; *argv; ++argv) {
		if (strchr(*argv, '=')) continue;

		name_len = strlen(*argv);

		for (; *env; env++) {
			if (!strncmp(*env, *argv, name_len)) {
				value = *env + name_len;
				if (!*value || *value == '=') {
					printf("%s%c",
					       *value ? value + 1 : value,
					       '\n' * !zero);
					matches++;
					break;
				}
			}
		}
	}

	return !!(matches - (argc - optind));
}
